//
//  PhotoBrowserViewController.swift
//  glzbowei
//
//  Created by 高伦展 on 2018/3/2.
//  Copyright © 2018年 glz. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 可重用标识符号
private let PhotoBrowserViewCellId = "PhotoBrowserViewCellId"

//照片浏览器
class PhotoBrowserViewController: UIViewController {

    //照片 url 数组
    private var urls:[URL]
    //当前选中的照片索引
    private var currentIndexPath:IndexPath
    
    @objc func close(){ 
        dismiss(animated: true, completion: nil)
    }
    
    @objc func save(){
        
        let cell = collectionView.visibleCells[0] as! PhotoBrowserCell
        
        guard let image = cell.imageView.image else{
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(PhotoBrowserViewController.image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    @objc private func image(image:UIImage,didFinishSavingWithError error:Error?,contextInfo:AnyObject?){
        let message = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfo(withStatus: message)
    }
    
    // MARK: - 构造函数
    init(urls:[URL],indexPath:IndexPath){
        self.urls = urls
        self.currentIndexPath = indexPath
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        let rect = UIScreen.main.bounds
        view = UIView(frame: rect)
        
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
  
        //定位到点击的图片
        collectionView.scrollToItem(at: currentIndexPath, at: .centeredHorizontally, animated: false)
    }

    // MARK: - 懒加载控件
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: PhotoBrowserViewFlowLayout())
    
    private lazy var closeButton:UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.white, imgName: nil, backColor: UIColor.darkGray)

    private lazy var saveButton:UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.white, imgName: nil, backColor: UIColor.darkGray)
    
    private class PhotoBrowserViewFlowLayout: UICollectionViewFlowLayout {
        override func prepare() {
            super.prepare()
            
            itemSize = collectionView!.bounds.size
            minimumLineSpacing = 0
            minimumInteritemSpacing = 0
            
            scrollDirection = .horizontal
            
            collectionView?.isPagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.bounces = false
        }
    }
}

extension PhotoBrowserViewController:UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoBrowserViewCellId, for: indexPath) as! PhotoBrowserCell
        
        cell.backgroundColor = UIColor.randomColor()
        cell.imageURL = urls[indexPath.item]
        cell.photoDelegate = self
        return cell
    }
}

extension PhotoBrowserViewController:PhotoBrowserCellDelegate{
    
    func photoBrowserCellDidClickImage() {
        close()
    }
}

//设置界面
extension PhotoBrowserViewController{
    
    private func setupUI(){
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        collectionView.frame = view.bounds
        
        closeButton.snp.makeConstraints { (make) in
            make.bottom.equalTo(view.snp.bottom).offset(-8)
            make.left.equalTo(view.snp.left).offset(8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        saveButton.snp.makeConstraints { (make) in
            make.bottom.equalTo(view.snp.bottom).offset(-8)
            make.right.equalTo(view.snp.right).offset(-8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        closeButton.addTarget(self, action: #selector(PhotoBrowserViewController.close), for: .touchUpInside)
        
        saveButton.addTarget(self, action: #selector(PhotoBrowserViewController.save), for: .touchUpInside)
        
        // 4. 准备控件
        prepareCollectionView()
    }
    
    private func prepareCollectionView(){
        
        collectionView.dataSource = self
        
        collectionView.register(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserViewCellId)
    }
}

extension PhotoBrowserViewController:PhotoBrowserDismissDelegate{
    func indexPathForDismiss() -> IndexPath {
        return collectionView.indexPathsForVisibleItems[0]
    }
    
    func imageViewForDismiss() -> UIImageView {
        let iv = UIImageView()
        
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        
        let cell = collectionView.visibleCells[0] as! PhotoBrowserCell
        iv.image = cell.imageView.image
        
        iv.frame =
           cell.scrollView.convert(cell.imageView.frame, to: UIApplication.shared.keyWindow!)
        
        return iv
    }
    
}
